package com.uroad.jilinpda.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.TextView;

import com.uroad.jilinpda.R;
import com.uroad.jilinpda.common.BaseActivity;
import com.uroad.jilinpda.common.GlobalData;
import com.uroad.jilinpda.fragment.SplashFragment;
import com.uroad.jilinpda.modle.CheckVersionMDL;
import com.uroad.jilinpda.presenter.LoginPresenter;
import com.uroad.jilinpda.presenter.MainPresenter;
import com.uroad.jilinpda.util.ObuKeepAlive;
import com.uroad.jilinpda.util.SPUtils;
import com.uroad.jilinpda.webservice.ActivateWS;
import com.uroad.jilinpda.widget.SYSDiaLogUtils;
import com.uroad.jilinpda.widget.TripDialog;
import com.uroad.lib.data.Constant;
import com.uroad.lib.widget.dialog.DialogHelper;

import java.lang.ref.WeakReference;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private SplashFragment splashFragment;
    private ViewStub viewStub;

    private TextView tv_name;
    private TextView tv_phone;
    private TextView my_order;
    private TextView tv_actvation;
    private TextView tv_testing;
    private TextView tv_setting;
    private TextView tv_net_stute;
    private ImageView iv_workout;
    private Handler mHandler = new Handler();
    private MainPresenter presenter;
    private TripDialog tripDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentLayoutWithoutTitle(R.layout.activity_main);
        delayedLoad();
        initPresenter();
        ObuKeepAlive.getInstance().initSdkHelper(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (presenter.isOnLine()){
            openActivity(LoginActivity.class);
            finish();
        }else{

        }
        presenter.getVersionInfo();
        setNet();
    }

    private void initPresenter(){
        presenter = new MainPresenter(this);
        presenter.attachView(this);
        presenter.checkAttach();
    }

    private void initViewStub(){
        viewStub.inflate();
        String recocode = (String) SPUtils.get(this, GlobalData.sp_recocode, "");
        String phone = (String) SPUtils.get(this, GlobalData.sp_phone, "");
        tripDialog = new TripDialog(this);
        tripDialog.setDismissAble(false);
        tv_name = findViewById(R.id.tv_name);
        tv_phone = findViewById(R.id.tv_phone);
        my_order = findViewById(R.id.my_order);
        tv_actvation = findViewById(R.id.tv_actvation);
        tv_testing = findViewById(R.id.tv_testing);
        tv_setting = findViewById(R.id.tv_setting);
        tv_net_stute = findViewById(R.id.tv_net_stute);
        iv_workout = findViewById(R.id.iv_workout);
        tv_name.setText("工号 "+recocode);
        tv_phone.setText(phone);
        my_order.setOnClickListener(this);
        tv_actvation.setOnClickListener(this);
        tv_testing.setOnClickListener(this);
        tv_setting.setOnClickListener(this);
        iv_workout.setOnClickListener(this);
        setNet();
    }

    private void setNet(){
        if ("WIFI".equals(Constant.NET)&&tv_net_stute != null){
            tv_net_stute.setText("当前网络状态：外网");
        }else if("4G".equals(Constant.NET)&&tv_net_stute != null){
            tv_net_stute.setText("当前网络状态：内网");
        }
    }

    public void showDownloadDialog(CheckVersionMDL mdl) {
        tripDialog.showCancelBtn(true);
        tripDialog.setTitle("发现新版本");
        tripDialog.setContent(mdl.getUpdatelog());
        tripDialog.setbtnConfirm("立即更新");
        tripDialog.setbtnCancel("稍后更新");
        tripDialog.setOnDialogClickListener(new TripDialog.OnDiglogClickListener() {
            @Override
            public void onConfirm() {
                presenter.downLoad(mdl.getDownloadurl());
            }

            @Override
            public void onCancel() {
                DialogHelper.endLoading();
                tripDialog.dismiss();
                finish();
                //                if (isShowUpdateDialog) {
                //                    if (isMustUpdate) {
                //                        finish();
                //                        System.exit(0);
                //                    }
                //                }
            }
        });
        tripDialog.show();
    }

    public void tripDialogContent(long progress){
        tripDialog.setContent("新版本下载中:"+progress+"%");
    }

    public void tripDialogDissmis(){
        tripDialog.dismiss();
    }

    public void showToast(String str){
        showShortToast(str);
    }

    public void logout(){
        openActivity(LoginActivity.class);
        finish();
    }

    public void onClick(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()){
            case  R.id.my_order:
                openActivity(ReleaserecordsActivity.class);
                break;
            case  R.id.tv_actvation:
                openActivity(OBUActivationMainActivity.class);
                break;
            case  R.id.tv_testing:
                bundle.putString("type","testing");
                openActivity(ETCActivation58GActivity.class ,bundle);
                break;
            case  R.id.tv_setting:
                openActivity(SettingActivity.class);
                break;
            case  R.id.iv_workout:
                SYSDiaLogUtils.showConfirmDialogType(MainActivity.this, "", "是否退出登录？", "", "确定", "取消", new SYSDiaLogUtils.ConfirmDialogListener() {
                    @Override
                    public void onClickButton(boolean clickLeft, boolean clickRight) {
                        if (clickLeft) {

                        } else if (clickRight) {
                            DialogHelper.showLoading(MainActivity.this, "");
                            presenter.logout();
                        }
                    }
                });
                break;
        }
    }


    private void delayedLoad(){
        splashFragment = new SplashFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.frame, splashFragment);
        transaction.commit();

        viewStub = (ViewStub)findViewById(R.id.content_viewstub);
        //1.判断当窗体加载完毕的时候,就把我们真正的布局加载进来
        getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                // 开启延迟加载
                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        //将viewstub加载进来
                        initViewStub();
                    }
                } );
            }
        });
        //2.判断当窗体加载完毕的时候执行,延迟一段时间是为了模拟做动画的耗时。
        getWindow().getDecorView().post(new Runnable() {

            @Override
            public void run() {
                // 开启延迟加载,也可以不用延迟可以立马执行（我这里延迟是为了实现fragment里面的动画效果的耗时）
                mHandler.postDelayed(new DelayRunnable(MainActivity.this, splashFragment) ,0);
            }
        });
    }

    static class DelayRunnable implements Runnable{
        private WeakReference<Context> contextRef;
        private WeakReference<SplashFragment> fragmentRef;

        public DelayRunnable(Context context, SplashFragment f) {
            contextRef = new WeakReference<>(context);
            fragmentRef = new WeakReference<>(f);
        }

        @Override
        public void run() {
            if(contextRef!=null){
                SplashFragment splashFragment = fragmentRef.get();
                if(splashFragment==null){
                    return;
                }
                FragmentActivity activity = (FragmentActivity) contextRef.get();
                FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
                transaction.remove(splashFragment);
                transaction.commit();
            }
        }
    }
}
